package com.yd.mvc.baseController.util;



import com.yd.app.util.BusinessException;
import com.yd.app.util.HexUtil;
import com.yd.app.util.XOR;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


public class AuthUtil {

	private static String skey = "angular";
	private static boolean skey_modify = true;
	private static String cookiePath = "/";
	private static boolean cookie_path_modify = true;
	private static String cookieDomain = ".angular.com";
	private static boolean cookie_domain_modify = true;

	private static String cookieName = "u";
	private static boolean cookie_name_modify = true;


	/**
	 * cookie中用户信息的分割符
	 */
	private static final String user_separator="#";


	
	/*
	 * private static final long EXPIERINTERVAL = 1000 * 60 * 3; private static
	 * final long UPDATEINTERVAL = 1000 * 60 * 1;
	 */

	public static String getCookieName() {
		return cookieName;
	}

	public void setCookieName(String cookieName) {
		if(cookie_name_modify){
			AuthUtil.cookieName = cookieName;
			cookie_name_modify = false;
		}
	}

	public void setSkey(String skey) {
		if(skey_modify){
			AuthUtil.skey = skey;
			skey_modify =false;
		}
	}

	public void setCookiePath(String cookiePath) {
		if(cookie_path_modify){
			AuthUtil.cookiePath = cookiePath;
			cookie_path_modify = false;
		}
	}

	public void setCookieDomain(String cookieDomain) {
		if(cookie_domain_modify){
			AuthUtil.cookieDomain = cookieDomain;
			cookie_domain_modify = false;
		}
	}
	
	public static String getCookiePath() {
		return cookiePath;
	}

	public static String getCookieDomain() {
		return cookieDomain;
	}



	private static long expierinterval = 1000 * 60 * 60;
	public static long getExpierinterval() {
		return expierinterval;
	}



	private static long updateinterval = 1000 * 60 * 20;

	public void setExpierinterval(long expierinterval) {
		AuthUtil.expierinterval = expierinterval;
		AuthUtil.updateinterval = AuthUtil.expierinterval / 3;
	}

	private static ThreadLocal<AuthedUser> threadLocal = new ThreadLocal<AuthedUser>();


	public static boolean auth(HttpServletRequest request,
			HttpServletResponse response) throws BusinessException {
		Cookie[] cookies = request.getCookies();
		if (cookies == null || cookies.length <= 0) {
			return false;
		}
		Cookie cookie = WebUtils.getCookie(request, cookieName);
		if(cookie==null) return false;
				try {
					String value = cookie.getValue();
					if(value==null||value.length()==0) return false;
					String userInfo = XOR.decoder(value.substring(1), skey);
					String[] userInfos = userInfo.split(user_separator);
					AuthedUser user = new AuthedUser(userInfos[0], userInfos[1],userInfos[2],userInfos[3],userInfos[4]);
					long time = HexUtil.hexTolong(HexUtil.hexStringToBytes(value.substring(41, 57)));
					long interval = System.currentTimeMillis() - time;
					// 令牌已过期
					if (interval > expierinterval) {
						return false;
					}
					// 达到更新时间，更新令牌信息
					if (interval >= updateinterval) {
						login(response, user.getUserId(), user.getUserName(),user.getRealName(),user.getCompanyName(),user.getPermCodeList());
					}
					threadLocal.set(user);
					return true;
				} catch (Exception e) {
					return false;
				}
	}


	public static void leave() {
		threadLocal.remove();
	}

	public static AuthedUser getCurrentUser() {
		return threadLocal.get();
	}


	public static Cookie login(HttpServletResponse response, String userId,
			String userName,String realName,String companyName,String permCodeList) throws Exception {
		//将角色信息转化为逗号分隔的字符串存储

		String userInfo=userId + user_separator+userName+user_separator+realName+user_separator+companyName+user_separator+(permCodeList.isEmpty()?"-":permCodeList);
		//因为如果roleStr为空，在分割字符串时会去掉它，导致数组长度少一，为方便处理所以当roleStr为空时，给他一个默认值
		Cookie authCookie = new Cookie(cookieName, String.format("1%s",XOR.encoder(userInfo, skey)));
		authCookie.setPath(cookiePath);
		//authCookie.setDomain(cookieDomain);
		authCookie.setMaxAge((int) expierinterval/1000);
		response.addCookie(authCookie);
		response.setHeader("P3P","CP=CAO PSA OUR");
		return authCookie;
	}

	/**
	 * 登出
     */
	public static void logout(HttpServletResponse response){
		AuthedUser user = AuthUtil.getCurrentUser();
		Cookie cookie = new Cookie(AuthUtil.getCookieName(),null);
		cookie.setPath(AuthUtil.getCookiePath());
		//cookie.setDomain(AuthUtil.getCookieDomain());
		cookie.setMaxAge(0);
		response.reset();
		response.addCookie(cookie);
	}
	public static class AuthedUser {
		private String userId;
		private String userName;
		private String realName;
		private String companyName;
		private String permCodeList;

		@Override
		public String toString() {
			return "AuthedUser{" +
					"userId='" + userId + '\'' +
					", userName='" + userName + '\'' +
					", realName='" + realName + '\'' +
					", companyName='" + companyName + '\'' +
					", permCodeList='" + permCodeList + '\'' +
					'}';
		}

		public AuthedUser(String userId, String userName,String realName,String companyName, String permCodeList) {
			this.userId = userId;
			this.userName = userName;
			this.realName = realName;
			this.companyName = companyName;
			this.permCodeList=permCodeList;
		}

		public String getPermCodeList() {
			return permCodeList;
		}

		public void setPermCodeList(String permCodeList) {
			this.permCodeList = permCodeList;
		}

		public String getUserId() {
			return userId;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserId(String userId) {
			this.userId = userId;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}

		public String getRealName() {
			return realName;
		}

		public void setRealName(String realName) {
			this.realName = realName;
		}

		public String getCompanyName() {
			return companyName;
		}

		public void setCompanyName(String companyName) {
			this.companyName = companyName;
		}
	}
}
